package com.china08.yxyapi.api.schwebsite.article;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.sws.SwsSection;
import com.china08.yxyapi.entity.db.sws.SwsSetting;
import com.china08.yxyapi.entity.db.sws.SwsSettingDomains;
import com.china08.yxyapi.entity.mg.sws.SwsArticle;
import com.china08.yxyapi.entity.mg.sws.SwsArticleForDailyAnalyze;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.SwsSectionRepository;
import com.china08.yxyapi.repository.db.SwsSettingDomainsRepository;
import com.china08.yxyapi.repository.db.SwsSettingRepository;
import com.china08.yxyapi.repository.mg.SwsArticleForDailyAnalyzeRepository;
import com.china08.yxyapi.repository.mg.SwsArticleRepository;
import com.china08.yxyapi.util.DateToolUtils;
import com.china08.yxyapi.util.DisposeCkContentUtil;

/**
 * 学校网站:文章详情
 * 
 * @author Ertao.Fang
 *
 */
@CrossOrigin
@RestController("SwsArticleDetailController")
public class SwsArticleDetailController extends YxyApiBaseController {

    @Autowired
    private SwsSectionRepository swsSectionRepository;

    @Autowired
    private SwsSettingDomainsRepository swsSettingDomainsRepository;

    @Autowired
    private SwsArticleRepository swsArticleRepository;

    @Autowired
    private SwsSettingRepository swsSettingRepository;

    @Autowired
    private SwsArticleForDailyAnalyzeRepository swsArticleForDailyAnalyzeRepository;

    @RequestMapping(value = "/api_yw/schwebsite/article", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel process(HttpServletRequest request, HttpServletResponse response,
            @RequestBody(required = false) ReqModel reqModel) {
        String domainName = getDomainName(request);
        Assert.isTrue(StringUtils.isNotBlank(domainName), "域名为空");
        // 通过域名获取学校ID
        SwsSettingDomains settingDomains = swsSettingDomainsRepository.findByDomainName(domainName);
        Assert.isTrue(null != settingDomains, "域名对象为空");
        String schoolId = settingDomains.getSchoolId();
        String articleId = reqModel.articleId;
        RespModel model = new RespModel();
        Assert.isTrue(StringUtils.isNotBlank(articleId), "文章ID为空");
        Integer auditStatus = 1;
        SwsArticle swsArticle = swsArticleRepository.findById(articleId);
        SwsSetting swsSetting = swsSettingRepository.findBySchoolId(schoolId);
        Assert.isTrue(null != swsSetting, "学校信息为空");
        if (null != swsSetting) {
            String schoolBadge = "";
            // 获取详情中的第一张图片作为推荐图片
            Document document = Jsoup.parse(swsArticle.getContent());
            Elements imgElements = document.select("img");

            for (Element imgElement : imgElements) {
                String style = imgElement.attr("style");
                style = style.replaceAll("max-width", "max-width_back");
                style = style.replaceAll("height", "height_back");
                style = style.replaceAll("max-height", "max-height_back");
                imgElement.attr("style", style);
            }
            swsArticle.setContent(document.html());
            if (imgElements.size() > 0) {
                schoolBadge = imgElements.get(0).attr("src");
            }
            if (StringUtils.isBlank(schoolBadge)) {
                schoolBadge = swsSetting.getSchoolBadge();
            }
            if (StringUtils.isBlank(schoolBadge)) {
                schoolBadge = "";
            }
            String schoolName = swsArticle.getTitle();
            String description = swsArticle.getContent();

            if (schoolName.length() >= 15) {
                schoolName = schoolName.substring(0, 15);
            }
            if (description.length() >= 30) {
                description = description.substring(0, 30);
            }
            description = Jsoup.parse(description).text();
            model.schoolBadge = schoolBadge;
            model.schoolName = schoolName;
            model.description = description;
        }

        Assert.isTrue(null != swsArticle, "文章列表 为空");
        String section1Id = "";
        String section2Id = "";
        section1Id = swsArticle.getSection1Id();
        section2Id = swsArticle.getSection2Id();

        // 文章日点击量
        SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String format = sFormat.format(date);
        String id = articleId + format;

        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        int month = aCalendar.get(aCalendar.MONTH) + 1;
        int day = aCalendar.get(aCalendar.DATE);
        int yearForPv = aCalendar.get(aCalendar.YEAR);
        // 获取学校ID
        SwsArticle findById = swsArticleRepository.findById(articleId);

        // 判断今天是否浏览过
        SwsArticleForDailyAnalyze forDailyAnalyze = swsArticleForDailyAnalyzeRepository.findById(id);
        if (forDailyAnalyze != null) {
            forDailyAnalyze.setPv(forDailyAnalyze.getPv() + 1l);
            swsArticleForDailyAnalyzeRepository.save(forDailyAnalyze);
        } else {
            SwsArticleForDailyAnalyze sAnalyze = new SwsArticleForDailyAnalyze();
            sAnalyze.setId(id);
            sAnalyze.setArticleId(articleId);
            sAnalyze.setDateForPv(date);
            sAnalyze.setDayForPv(day);
            sAnalyze.setMonthForPv(month);
            sAnalyze.setSchoolId(findById.getOwnerSchoolId());
            sAnalyze.setPv(1l);
            sAnalyze.setYearForPv(yearForPv);
            sAnalyze.setSection1Id(section1Id);
            sAnalyze.setSection2Id(section2Id);
            swsArticleForDailyAnalyzeRepository.save(sAnalyze);
        }

        String con = swsArticle.getContent();
        con = DisposeCkContentUtil.dispose(con);
        String con1 = con;
        con1 = DisposeCkContentUtil.dispose(con1);
        Document document = Jsoup.parse(con1);
        Elements div_elements = document.select("table");
        if (div_elements.size() > 0) {
            div_elements.wrap("<div style='overflow: scroll; max-width: 100%;'></div>");
        }
        String content_mobile = document.select("body").html();
        if (content_mobile.contains("http:")) {
            content_mobile = content_mobile.replace("http:", "https:");
        }
        model.content_mobile = content_mobile;
        if (con.contains("http:")) {
            con = con.replace("http:", "https:");
        }
        model.content = con;
        if (StringUtils.isNotBlank(swsArticle.getFaceImg())) {
            // if (swsArticle.getFaceImg().startsWith("https")) {
            // model.faceImg = swsArticle.getFaceImg().replace("https:", "");
            // } else {
            // model.faceImg = swsArticle.getFaceImg().replace("http:", "");
            // }
        } else {
            model.faceImg = swsArticle.getFaceImg();
        }
        model.showDate = DateToolUtils.format(swsArticle.getShowDate(), DateToolUtils.FORMAT_SHORT_YMD);
        model.summary = swsArticle.getSummary();
        model.title = swsArticle.getTitle();
        model.attachmentDownloadUrl = swsArticle.getAttachmentDownloadUrl();
        model.attachmentFileName = swsArticle.getAttachmentFileName();
        model.pv = swsArticle.getPv();
        Integer pv = swsArticle.getPv() + 1;

        swsArticle.setPv(pv);
        swsArticleRepository.save(swsArticle);

        model.author = swsArticle.getAuthor();
        model.senderName = swsArticle.getSenderName();
        SectionName sectionName = new SectionName();
        if (StringUtils.isNotBlank(section1Id) && StringUtils.isBlank(section2Id)) {
            SwsSection swsSection = swsSectionRepository.findById(section1Id);
            sectionName.sectionName1 = swsSection.getSectionName();

        } else if (StringUtils.isNotBlank(section2Id) && StringUtils.isBlank(section1Id)) {
            SwsSection swsSection = swsSectionRepository.findById(section2Id);
            sectionName.sectionName2 = swsSection.getSectionName();
        } else if (StringUtils.isNotBlank(section2Id) && StringUtils.isNotBlank(section1Id)) {
            SwsSection swsSection = swsSectionRepository.findById(section1Id);
            sectionName.sectionName1 = swsSection.getSectionName();
            SwsSection swsSection2 = swsSectionRepository.findById(section2Id);
            sectionName.sectionName2 = swsSection2.getSectionName();
        } else {
            sectionName.sectionName2 = "栏目为空";
        }
        model.sectionName = sectionName;
        ArticleModel articleModel1 = new ArticleModel();

        SwsArticle article1 = null;
        SwsArticle swsArticle2 = null;
        // 查询一级栏目下文章详情中上一篇下一篇标题
        if (StringUtils.isNotBlank(section1Id) && StringUtils.isBlank(section2Id)) {
            Boolean isSticky = swsArticle.getIsSticky();
            if (isSticky) {
                // 下一篇
                swsArticle2 = swsArticleRepository
                        .findTop1ByOwnerSchoolIdAndSection1IdAndAuditStatusAndIsStickyAndShowDateLessThanOrderByIsStickyAscShowDateDesc(
                                schoolId, section1Id, auditStatus, true, swsArticle.getShowDate());
                if (swsArticle2 == null) {
                    swsArticle2 = swsArticleRepository
                            .findTop1ByOwnerSchoolIdAndSection1IdAndAuditStatusAndIsStickyOrderByIsStickyAscShowDateDesc(
                                    schoolId, section1Id, auditStatus, false);
                }
            } else {
                swsArticle2 = swsArticleRepository
                        .findTop1ByOwnerSchoolIdAndSection1IdAndAuditStatusAndIsStickyAndShowDateLessThanOrderByIsStickyAscShowDateDesc(
                                schoolId, section1Id, auditStatus, false, swsArticle.getShowDate());
            }
            if (isSticky) {
                // 上一篇
                article1 = swsArticleRepository
                        .findTop1ByOwnerSchoolIdAndSection1IdAndAuditStatusAndIsStickyAndShowDateGreaterThanOrderByIsStickyAscShowDateAsc(
                                schoolId, section1Id, auditStatus, true, swsArticle.getShowDate());
            } else {
                article1 = swsArticleRepository
                        .findTop1ByOwnerSchoolIdAndSection1IdAndAuditStatusAndIsStickyAndShowDateGreaterThanOrderByIsStickyAscShowDateAsc(
                                schoolId, section1Id, auditStatus, false, swsArticle.getShowDate());
                if (article1 == null) {
                    article1 = swsArticleRepository
                            .findTop1ByOwnerSchoolIdAndSection1IdAndAuditStatusAndIsStickyOrderByIsStickyAscShowDateAsc(
                                    schoolId, section1Id, auditStatus, true);
                }
            }
            // 查询二级栏目下文章详情中上一篇下一篇标题
        } else if (StringUtils.isNotBlank(section2Id)) {
            Boolean isSticky = swsArticle.getIsSticky();
            if (isSticky) {
                // 下一篇
                swsArticle2 = swsArticleRepository
                        .findTop1ByOwnerSchoolIdAndSection2IdAndAuditStatusAndIsStickyAndShowDateLessThanOrderByIsStickyAscShowDateDesc(
                                schoolId, section2Id, auditStatus, true, swsArticle.getShowDate());
                if (swsArticle2 == null) {
                    swsArticle2 = swsArticleRepository
                            .findTop1ByOwnerSchoolIdAndSection2IdAndAuditStatusAndIsStickyOrderByIsStickyAscShowDateDesc(
                                    schoolId, section2Id, auditStatus, false);
                }
            } else {
                swsArticle2 = swsArticleRepository
                        .findTop1ByOwnerSchoolIdAndSection2IdAndAuditStatusAndIsStickyAndShowDateLessThanOrderByIsStickyAscShowDateDesc(
                                schoolId, section2Id, auditStatus, false, swsArticle.getShowDate());
            }
            if (isSticky) {
                // 上一篇
                article1 = swsArticleRepository
                        .findTop1ByOwnerSchoolIdAndSection2IdAndAuditStatusAndIsStickyAndShowDateGreaterThanOrderByIsStickyAscShowDateAsc(
                                schoolId, section2Id, auditStatus, true, swsArticle.getShowDate());
            } else {
                article1 = swsArticleRepository
                        .findTop1ByOwnerSchoolIdAndSection2IdAndAuditStatusAndIsStickyAndShowDateGreaterThanOrderByIsStickyAscShowDateAsc(
                                schoolId, section2Id, auditStatus, false, swsArticle.getShowDate());
                if (article1 == null) {
                    article1 = swsArticleRepository
                            .findTop1ByOwnerSchoolIdAndSection2IdAndAuditStatusAndIsStickyOrderByIsStickyAscShowDateAsc(
                                    schoolId, section2Id, auditStatus, true);
                }
            }
        }
        if (article1 != null) {
            articleModel1.aritcleId = article1.getId();
            articleModel1.title = article1.getTitle();
        }
        ArticleModel articleModel2 = new ArticleModel();
        if (swsArticle2 != null) {
            articleModel2.aritcleId = swsArticle2.getId();
            articleModel2.title = swsArticle2.getTitle();
        }
        model.nextTitle = articleModel2;
        model.lastTitle = articleModel1;
        return model;
    }

    protected static class ReqModel extends YxyApiReqModel {

        public String articleId;

    }

    protected static class ArticleModel {

        public String aritcleId;

        public String title;
    }

    protected static class SectionName {

        public String sectionName1;

        public String sectionName2;
    }

    protected static class RespModel extends YxyApiRespModel {

        public ArticleModel lastTitle;

        public ArticleModel nextTitle;

        public String content;

        public String content_mobile;

        public String faceImg;

        public String title;

        public String summary;

        public String showDate;

        public SectionName sectionName;

        public Integer pv;

        public String senderName;

        public String author;

        public String attachmentFileName;

        public String attachmentDownloadUrl;

        public String schoolBadge;

        public String schoolName;

        public String description;

    }

}
